package mystruts;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import vo.Person;

import com.opensymphony.xwork2.ActionSupport;

import dao.PersonDao;

public class PersonAction extends ActionSupport{

	public String addform() throws Exception {
		this.LOG.info("PersonAction.addform....");
		return "addform";
	}
	
	public String add() throws Exception {
		this.LOG.info("PersonAction.add....");
		this.LOG.info("Username"+vo.getUsername());
		this.LOG.info("Tel"+vo.getTel());
		//dao.PersonDao.this.insert(vo.getUsername());
		PersonDao dao = new PersonDao();
		dao.insert(vo);
		java.util.ArrayList<Person> list= shopcar();
		list.add(vo);
		
		//HttpSession session = ServletActionContext.getRequest().getSession();
		return "add";
	}
	
	public String list() throws Exception {
		this.LOG.info("PersonAction.list....");
		//this.setRslist(this.shopcar());
		return "list";
	}
	
	public String updateform() throws Exception {
		this.LOG.info("PersonAction.updateform....");
		this.setVo(shopcar().get(index));/*jsp取出表單多顯示這筆資料*/
		return "updateform";
	}
	
	public String update() throws Exception {
		this.LOG.info("PersonAction.update....");
		PersonDao dao = new PersonDao();
		dao.insert(vo);
		java.util.ArrayList<Person> list= shopcar();
		list.set(index, vo);//更新新資料
		return "update";
	}
	
	public String delete() throws Exception {
		this.LOG.info("PersonAction.delete....");
		java.util.ArrayList<Person> list= shopcar();
		list.remove(index);//刪除資料
		return list();
	}
	
	
	java.util.ArrayList<Person> shopcar(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		//從記憶體拿資料出來
		java.util.ArrayList<Person> list 
			= (java.util.ArrayList<Person>)session.getAttribute("list");
		if(list == null){
			list = new java.util.ArrayList<Person>();
			session.setAttribute("list", list);
		}
		return list;
	}
	
	Person vo;

	public Person getVo() {
		return vo;
	}

	public void setVo(Person vo) {
		this.vo = vo;
	}
	//java.util.ArrayList<Person> rslist;

	public java.util.ArrayList<Person> getRslist() {
		//return rslist;
		return shopcar();
	}
	
	int index;

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}
	
	
	
	/*
	public void setRslist(java.util.ArrayList<Person> rslist) {
		this.rslist = rslist;
	}
	*/
}
